<?php

class InvestmentAction extends BaseAction{
	protected function _initialize(){
		parent::_initialize();
		if(empty($this->user_session)){
			redirect(U('Login/index'));
		}
		$user_session = D('User')->get_user($this->user_session['uid']);
		$user_session['last'] = $this->user_session['last'];
		$this->user_session = $user_session;
		$this->assign('user_session',$this->user_session);
     /*
		//授信统计
		$pledges = D('Pledges')->where(array('uid'=>$this->user_session['uid']))->find();
		$this->assign('pledges',$pledges);

		if($this->user_session['staff_uid']){
			$escrow_staff  = M('Escrow_staff');
			$this->staff_show = $escrow_staff->where(array('id'=>$this->user_session['staff_uid']))->find();
			$this->assign('staff_show',$this->staff_show);
			if(IS_GET){
				$staff_list = $escrow_staff->field('`id`,`name`,`qq`')->select();
				$this->assign('staff_list',$staff_list);
			}
		}
		 */

	}
	//我要借出
	public function lend(){

		$Db_pledge = D('pledges');
		$Db_borrows       = D('Borrows');
		$Db_pledge_domain = D('Pledge_domain');
		$borrows_condition['status'] = 1;
		$t = intval($_GET['t']);
		if($t == 1){
			$orderby = '`ExpiredAt` DESC';
			$t = 2;
		}elseif($t == 2){
			$orderby = '`ExpiredAt` ASC';
			$t = 1;
		}
		if(empty($t)) $orderby = '`bid` DESC';
		$this->assign('t',$t);
		$tt = intval($_GET['tt']);
		if($tt == 3){
			$orderby = '`Amount` ASC';
 			$tt = 4;
		}elseif($tt == 4){
			$orderby = '`Amount` DESC';
			$tt = 3;
		}
		$this->assign('tt',$tt);
		$ttt = intval($_GET['ttt']);
		if($ttt == 5){
			$orderby = '`Rate` ASC';
			$ttt = 6;
		}elseif($ttt == 6){
			$orderby = '`Rate` DESC';
			$ttt = 5;
		}
		$this->assign('ttt',$ttt);

		$lc = intval($_GET['lc']);
		if($lc == 7 || $lc == 15){
			$borrows_condition['LoanCycleDay'] = $lc;
		}else if($lc >= 30 ){
			$borrows_condition['LoanCycleMonth'] = $lc/30;
		}
		$this->assign('lc',$lc ? $lc : 0);

		$maxa =  intval($_GET['maxa']);
		$mina = intval($_GET['mina']);
		if($maxa && empty($mina)){
			$borrows_condition['Amount'] = array('lt',$maxa);
			$mx = 1;
		}else if($mina && empty($maxa)){
			$borrows_condition['Amount'] = array('gt',$maxa);
			$mx = 3;
		}else if($maxa && $mina){
			$borrows_condition['Amount'] = array('between',array($mina,$maxa));
			$mx = 2;
		}
		$this->assign('mx',$mx ? $mx : 0);
		//排除自己
		$borrows_condition['uid'] = array('neq',$this->user_session['uid']);

		$borrowsList = $Db_borrows->where($borrows_condition)->order($orderby)->select();

		//剩余满标天数
		$startdate = date('Y-m-d',time());
		foreach($borrowsList as &$val){
			$val['surplus_date'] = getBetweenTwoDate($startdate ,$val['ExpiredAt']);
		}

		$this->assign('borrowsList',$borrowsList);

		$this->display();
	}

	//我要借出列表
	public function lendList(){
		$Db_borrows       = D('Borrows');
		$status = intval($_GET['state']);
		switch($status){
			case 1:
				$conditions['status'] = '1';
				break;
			case 2:
				$conditions['status'] = '2';
				break;
			case 3:
				$conditions['status'] = '3';
				break;
			case 4:
				$conditions['status'] = '4';
				break;
		}
		$this->assign('state',$status ? $status : 0);
		//TODO
		$conditions['inves_uids'] =  array('like',"%{$this->user_session['uid']}%");
		$borrowsList = $Db_borrows->where($conditions)->order('`bid` DESC')->select();
		$Db_investment = D('Investment');
		//($borrowsList);die;
		foreach($borrowsList as $key => $borrows){
			//一个人投资多次
			$investment = $Db_investment->where( array('did'=>$borrows['bid'],'uid'=>$this->user_session['uid']))->select();
			foreach($investment as &$invest){
				//总收本息 = 投资金额 + 每期利息收益 * 期数 (7天,15天,30 天 算一期  ； 2个月-12个月 一个月一期)
				$invest['zong_shoubenxi'] = $invest['Amount'] + $invest['nsy'] * $borrows['periods'];
				$borrowsList[$key]['get_all_menory'] += $invest['zong_shoubenxi']; //累加每次投资的总收本息
				$borrowsList[$key]['get_all_TR_principal'] += $invest['TR_principal'];//累加每次投资的已收本息
				$borrowsList[$key]['get_all_nsy'] += $invest['nsy'];//累加每次投资额
				$borrowsList[$key]['get_all_Amount'] += $invest['Amount'];//累加每次投资额
				$borrowsList[$key]['get_all_Amountdx'] = number2Chinese($borrowsList[$key]['get_all_Amount']);//累加每次投资额

			}
			$borrowsList[$key]['investmentdata'] = $investment;
		}

	//dump($borrowsList);die;


		$this->assign('borrowsList',$borrowsList);
		$this->display();
	}

	public function getInvestmentdata(){
		if(IS_POST){
			$bid = intval($_POST['id']) ? intval($_POST['id']) : 0;
			if($bid <= 0){
				$return = array('error'=>-1,'title'=>'获取信息失败','msg'=>'系统没有查到该记录');
				$this->ajaxReturn($return);
			}
			$Db_investment = D('Investment');
			$investment = $Db_investment->where( array('did'=>$bid,'uid'=>$this->user_session['uid']))->select();
			if(empty($investment)){
				$return = array('error'=>-1,'title'=>'获取信息失败','msg'=>'系统无法找到该条记录！');
				$this->ajaxReturn($return);
			}

			$table = '';
			$table .= '<div class="table-responsive">
					 	<table class=" table table-bordered table-striped table-hover">
							<thead>
						<tr>
							<th>投资人</th>
							<th>投资金额</th>
							<th>投资时间</th>
							<th>年利率</th>
							<th>收款周期</th>
							<th>每期利息收益</th>
							<th>总收本息</th>
							<th>已收本息</th>
							<th>状态</th>
						</tr>
						</thead>
						<tbody class="text-center">';

			foreach($investment as $val){
				$time = date('Y-m-d',$val['itime']);
				// 总收本息 = 投资金额 + 每期收益 * 期数
				$duoshaoqishu = $val['LoanCycle'] / 30;
				if($duoshaoqishu <= 1){
					$duoshaoqishu = 1; //7天,15天,30 天 算一期
				}
				$TR_principal_all = $val['Amount'] + $val['nsy'] * $duoshaoqishu;
//'投资状态：1投资中，2收款中，3退款中，4 借款收回完成，0流标',
				switch($val['status']){
					case 0 :
						$status = '流标';
						break;
					case 1:
						$status = '正在投资';
						break;
					case 2:
						$status = '收款中';
						break;
					case 3:
						$status = '退款中';
						break;
					case 4:
						$status = '借款收回完成';
						break;
				}
				$table .= "<tr>
							<td>{$val['iname']}</td>
							<td>￥{$val['Amount']}/{$val['Amountdx']}元</td>
							<td>{$time}</td>
							<td>{$val['Rate']}</td>
							<td>{$val['LoanCycle']} 天</td>
							<td>￥{$val['nsy']}</td>
							<td>￥{$TR_principal_all}</td>
							<td>￥{$val['TR_principal']}</td>
							<td>$status</td>
				</tr>";
			}

		$table .= '</tbody></table></div>';


			$return = array('error'=>0,'title'=>'详细投资信息列表','msg'=>'成功','htmldata'=>$table);
			$this->ajaxReturn($return);
		}
	}

	//取消投资
	public function cancelInvestment(){
		/***
		 * 解冻资金，增加账号可用额，减少借出总额，
		 * 还需要删除Borrows里的inves_uids记录和减少投资进度，
		 * 减少investor_tatol 总投资数
		 * 增加needAmount还需要投资金额
		 */
		if($this->isAjax()){
			//file_put_contents('jjjjjjj.log',print_r($_POST,true));
			$bid = intval($_POST['id']) ? intval($_POST['id']) : 0;
			if($bid > 0){
				$Db_borrows       = D('Borrows');
				$conditions['bid'] = $bid;
				$conditions['inves_uids'] = array('like',"%{$this->user_session['uid']}%");
				$borrows = $Db_borrows->where($conditions)->find();
				if(!empty($borrows)){
					//投资人记录
					$Db_investment = D('Investment');
					$investment_con['did'] = $borrows['bid'];
					$investment_con['uid'] = $this->user_session['uid'];
					//一人投资多次
					$investment   =  $Db_investment->where($investment_con)->select();
					$Db_user    = D('User');
					$Db_pledges = D('Pledges');
					$del_id = array();
					$inves_uids = explode(',',$borrows['inves_uids']);
					//echo '老的uids:'.$borrows['inves_uids']."<br/>";
					foreach($investment as $val){
						 //$touzie['Amount'] = $val['Amount'];
						 // 解冻资金，增加账号可用额
						 $Db_user->where('`uid`='.$this->user_session['uid'])->setDec('freeze_money',$val['Amount']);
						 $Db_user->where('`uid`='.$this->user_session['uid'])->setInc('now_money',$val['Amount']);
						 //减少借出总额
						 $Db_pledges->where('`uid`='.$this->user_session['uid'])->setDec('lend_total',$val['Amount']);
						 $invesing['invesing'] = intval((($borrows['Amount'] -($val['Amount'] + $borrows['needAmount'])) / $borrows['Amount']) * 100);//投资进度
						 $Db_borrows->where('`bid`='.$borrows['bid'])->save($invesing);
						 $Db_borrows->where('`bid`='.$borrows['bid'])->setInc('needAmount',$val['Amount']);//增加还需要投资的金额
						 $Db_borrows->where('`bid`='.$borrows['bid'])->setDec('investor_tatol',1);//减少总投资数
						 //最后删除
						 $del_iid[] = $val['iid'];
					}

					//echo '新的uids:'.$new_inves_uids;die;
					$del_con['iid'] = array('in',$del_iid);
					if($Db_investment->where($del_con)->delete()){
						//移除投资inves_uids记录
						foreach($inves_uids as $k=>$v){
							if($v == $this->user_session['uid']){
								unset($inves_uids[$k]);
							}
						}
						$new_inves_uids['inves_uids'] = implode(',',$inves_uids);
						$Db_borrows->where('`bid`='.$borrows['bid'])->data($new_inves_uids)->save();

						$return = array('error'=>0,'title'=>'取消成功','msg'=>'资金已经解冻！');
						$this->ajaxReturn($return);
					}else{
						$return = array('error'=>-1,'title'=>'错误','msg'=>'噢，取消出错了！');
						$this->ajaxReturn($return);
					}

				}else{
					$return = array('error'=>-1,'title'=>'错误','msg'=>'暂无记录');
					$this->ajaxReturn($return);
				}

			}else{
				$return = array('error'=>-1,'title'=>'错误','msg'=>'非法访问');
				$this->ajaxReturn($return);
			}


		}else{
			exit();

		}
	}

	//自动投放
	public function automatic(){
		$Db_automatic = D('Automatic');
		if(IS_POST){

			$aid = intval($_POST['id']) ? intval($_POST['id']): 0;
			if($aid > 0){
				$del_condition['uid'] = $this->user_session['uid'];
				$del_condition['aid'] = $aid;
				$del_condition['autotype'] = 1;
				$now_automatic = $Db_automatic->where($del_condition)->find();
				if(!empty($now_automatic)){
					if($Db_automatic->where($del_condition)->delete()){
						//4、若删除自动投标配置，您账户内对应的冻结金额将自动转换为可用余额；
						$Db_user = D('User');
						//退还金额 = 自动投标总额 - 已投资金额
						$get_back_monery = $now_automatic['total_amount'] - $now_automatic['has_meoney'];
						//用户的金额增加setInc
						$u_info = $Db_user->where(array('uid'=>$this->user_session['uid']))->setInc('now_money',$get_back_monery);
						//用户冻结金减少 setDec
						$u_info = $Db_user->where(array('uid'=>$this->user_session['uid']))->setDec('freeze_money',$get_back_monery);
						echo json_encode(array('error'=>0,'msg'=>'删除成功.'));exit;
					}else{
						echo json_encode(array('error'=>-1,'msg'=>'删除失败,请重试.'));exit;
					}
				}else{
					echo json_encode(array('error'=>-1,'msg'=>'不存在的记录'));exit;
				}
			}else{
				echo json_encode(array('error'=>-1,'msg'=>'不存在的记录'));exit;
			}
		} // END POST

		// 'invalid'=>0 失效配置， ,'invalid'=>1 有效配置，进入默认1
		$auto_condition['uid'] = $this->user_session['uid'];
		$auto_condition['autotype'] = 1;
		$invalid = intval($_GET['invalid']);
		if($invalid == 1){
			$state = 1;
			$auto_condition['invalid'] = 1;
		}elseif($invalid == 2){
			$auto_condition['invalid'] = 0;
			$state = 2;
		}
		$automaticList =  $Db_automatic->where($auto_condition)->select();

		$count_user_times = $Db_automatic->where(array('uid'=>$this->user_session['uid'],'autotype'=>1))->count();

		//每个人最多可以设置 5 个自动投标
		$this->assign('count_user_times',$count_user_times);
		$this->assign('automaticList',$automaticList);
		$this->assign('state',$state ? $state : 1);
		$this->display();
	}

	/***
	 * 什么是自动投标？
	自动投标即系统为借出者自动对借入标进行投标的工具。借出者可根据自己的风险偏好、投资习惯在自动投标中设置借款金额与最低利率，若有符合相应条件的借款出现，系统将自动帮借出者完成投标。
	自动投标规则说明
	1、每位用户允许添加5个自动投标配置；
	2、账户内有可用余额方能设置自动投标配置，且自动投标所设金额不能高于账户可用余额；
	3、成功设置自动投标配置后，系统将自动冻结您账户内相应的可用余额；
	4、若删除自动投标配置，您账户内对应的冻结金额将自动转换为可用余额；
	5、若按照您设置的自动投标配置，系统为您成功投完所设置的金额后，该自动投标配置自动转为失效配置；
	6、当一个借入列表满足多个设置自动投标的用户时，系统优先选择最低利率设置最低的用户完成投标；如设置的最低利率相同，系统则优先选择提交时间最早的用户完成投标；
	 */
	public function createAutomatic(){
		if(IS_POST){

			$Db_automatic = D('Automatic');
			$count_user_times = $Db_automatic->where(array('uid'=>$this->user_session['uid'],'autotype'=>1))->count();
			if($count_user_times > 5){
				exit(json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'每位用户允许添加5个自动投标配置','reloadurl'=>U('Investment/automatic'))));
			}
			$AUTO_POST['uid']               = $this->user_session['uid'];
			$AUTO_POST['autotype']          = 1;
			$AUTO_POST['available_meoney']  = $_POST['Aquotas']; //可用金额 ',
			$AUTO_POST['total_amount']      = $_POST['Amount']; //'投标总额',
			$AUTO_POST['MinRate']           = $_POST['MinRate'];  //'利率',
			if(!empty($_POST['LoanCycleDay'])) $AUTO_POST['LoanCycleDay']      = $_POST['LoanCycleDay'];
			if(!empty($_POST['LoanCycleMonth']))$AUTO_POST['LoanCycleMonth']    = $_POST['LoanCycleMonth'];
			$AUTO_POST['addTime']           = time();
			$AUTO_POST['invalid']           = 1;
			if(empty($_POST['Amount'])){
			  exit(json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'投标总额不可以为空','reloadurl'=>U('Investment/createAutomatic'))));
			}
			if($_POST['MinRate'] > 25){
				exit(json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'最低利率不能超过25%','reloadurl'=>U('Investment/createAutomatic'))));
			}
			$Db_user = D('User');
			$userInfo  = $Db_user->field(true)->where('`uid`='.$this->user_session['uid'])->find();
			if($userInfo['now_money'] < $_POST['Amount'] ){
				exit(json_encode(array('error'=>-1,'title'=>'账号余额不足','msg'=>'您的账号余额不足,不能设置自动投标！','reloadurl'=>U('Investment/createAutomatic'))));
			}


			if($Db_automatic->add($AUTO_POST)){
				//成功设置自动投标配置后，系统将自动冻结您账户内相应的可用余额；
				//冻结金额 【投标xxxx 冻结资金】
				$Db_user_money_list = M('User_money_list');
				$money_list_data['desc']       = "自动投标设置，冻结资金";
				$money_list_data['type']       = 4;
				$money_list_data['time']       = time();
				$money_list_data['uid']        = $this->user_session['uid'];
				$money_list_data['money']      = $_POST['Amount'];
				$money_list_data['now_money']  = $this->user_session['now_money'] -  $_POST['Amount'];
				//用户的金额减少
				$u_info = $Db_user->where(array('uid'=>$this->user_session['uid']))->setDec('now_money',$_POST['Amount']);
				//用户冻结金额增加
				$u_info = $Db_user->where(array('uid'=>$this->user_session['uid']))->setInc('freeze_money',$_POST['Amount']);
				$f_info = $Db_user_money_list->add($money_list_data);
				exit(json_encode(array('error'=>0,'title'=>'设置成功','msg'=>'成功设置自动投标配置','reloadurl'=>U('Investment/automatic'))));
			}else{
				exit(json_encode(array('error'=>-1,'title'=>'提交失败','msg'=>'请重新提交','reloadurl'=>U('Investment/createAutomatic'))));
			}
		}
		$this->display();
	}





	//汇款继投
	public function keepInvest(){
		$Db_automatic = D('Automatic');
		$conditions['uid'] = $this->user_session['uid'];
		$conditions['autotype'] = 2;
		$automaticList = $Db_automatic->where($conditions)->find();
		if(IS_POST){
			$Db_automatic = D('Automatic');
			$AUTO_POST['uid']                    = $this->user_session['uid'];
			$AUTO_POST['autotype']               = 2;
			$AUTO_POST['reserved_meoney']        = $_POST['ReservedAmount']; //'保留金额，
			$AUTO_POST['MinRate']                = $_POST['MinRate'];  //'利率',
			if(!empty($_POST['LoanCycleDay']))   $AUTO_POST['LoanCycleDay']      = $_POST['LoanCycleDay'];
			if(!empty($_POST['LoanCycleMonth'])) $AUTO_POST['LoanCycleMonth']    = $_POST['LoanCycleMonth'];
			$AUTO_POST['addTime']           = time();
			$AUTO_POST['invalid']           = 1;

			if(empty($_POST['ReservedAmount'])){
				exit(json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'保留金额不可以为空','reloadurl'=>U('Investment/keepInvest'))));
			}
			if($_POST['MinRate'] > 25){
				exit(json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'最低利率不能超过25%','reloadurl'=>U('Investment/keepInvest'))));
			}
			$AUTO_POST['aid']     = intval($_POST['aid']);
			$AUTO_POST['is_open'] = intval($_POST['is_open']);

			if(isset($_POST['aid']) &&  $AUTO_POST['aid'] >0){
				if($AUTO_POST['is_open'] == 1){ $msg ='【成功开启】回款续投配置';}else{ $AUTO_POST['invalid'] = 0;$msg ='【成功关闭】回款续投配置';}
				if($Db_automatic->save($AUTO_POST)){

					exit(json_encode(array('error'=>0,'title'=>'设置成功','msg'=>'成功设置回款续投配置'.$msg,'reloadurl'=>U('Investment/keepInvest'))));
				}else{
					echo json_encode(array('error'=>-1,'title'=>'修改失败','msg'=>'请重新提交','reloadurl'=>U('Investment/keepInvest')));
				}
			}else{
				if($Db_automatic->add($AUTO_POST)){
					echo json_encode(array('error'=>0,'title'=>'设置成功','msg'=>'成功设置回款续投配置','reloadurl'=>U('Investment/keepInvest')));
					//exit(json_encode(array('error'=>0,'title'=>'设置成功','msg'=>'成功设置回款续投配置','reloadurl'=>U('Investment/keepInvest'))));
				}else{
					echo json_encode(array('error'=>-1,'title'=>'提交失败','msg'=>'请重新提交','reloadurl'=>U('Investment/keepInvest')));
					//exit(json_encode(array('error'=>-1,'title'=>'提交失败','msg'=>'请重新提交','reloadurl'=>U('Investment/keepInvest'))));
				}
			}

		}

		$LoanCycleDay   =  explode(',',$automaticList['LoanCycleDay']);
		foreach($LoanCycleDay as $v){
			switch($v){
				case 7 :
					$LoanCycleDay['7'] = $v;
					break;
				case 15:
					$LoanCycleDay['15'] = $v;
					break;
			}
		}
		$LoanCycleMonth = explode(',',$automaticList['LoanCycleMonth']);
		foreach($LoanCycleMonth as $v){
			switch($v){
				case 1 :
					$LoanCycleMonth['1'] = $v;
					break;
				case 2 :
					$LoanCycleMonth['2'] = $v;
					break;
				case 3 :
					$LoanCycleMonth['3'] = $v;
					break;
				case 4 :
					$LoanCycleMonth['4'] = $v;
					break;
				case 5 :
					$LoanCycleMonth['5'] = $v;
					break;
				case 6 :
					$LoanCycleMonth['6'] = $v;
					break;
				case 7 :
					$LoanCycleMonth['7'] = $v;
					break;
				case 8 :
					$LoanCycleMonth['8'] = $v;
					break;
				case 9 :
					$LoanCycleMonth['9'] = $v;
					break;
				case 10 :
					$LoanCycleMonth['10'] = $v;
					break;
				case 11 :
					$LoanCycleMonth['11'] = $v;
					break;
				case 12:
					$LoanCycleMonth['12'] = $v;
					break;
			}
		}
		$automaticList['reserved_meoney'] = intval($automaticList['reserved_meoney']);

		$this->assign('LoanCycleMonth',$LoanCycleMonth);
		$this->assign('LoanCycleDay',$LoanCycleDay);
		$this->assign('automaticList',$automaticList);
		$this->display();
	}

	//借贷详细页面
	public function loanScheme(){

		$dkid = intval($_GET['dkid']) ? intval($_GET['dkid']) : 0;
		if($dkid <= 0){
			$this->error('进入方式不对！',U('Financing/index'));
		}
		$Db_pledge = D('Pledges');
		$Db_borrows       = D('Borrows');
		$conditions['bid'] = $dkid;

		$borrowsList = $Db_borrows->where($conditions)->find();
		$show_detail = false;
		if($this->user_session['uid']){
			//如果登录了，则检查是否是投资人
			$uids = explode(',',$borrowsList['inves_uids']);
			if(in_array($this->user_session['uid'],$uids)){
				$conditions['inves_uids'] =  array('like',"%{$this->user_session['uid']}%");
				$show_detail = true;
				//echo '当前uid:'.$this->user_session['uid']." 存在：==>".$borrowsList['inves_uids'];
			}
		}else{ //游客
			$conditions['status'] = 1;
			$show_detail = false;
		}
		$borrowsList = $Db_borrows->where($conditions)->find();

		$borrowsList['yuelx'] = number_format(($borrowsList['Rate']/12),4);
		if(!empty($borrowsList['LoanCycleMonth']) || intval($borrowsList['LoanCycleMonth']) != 0){
			//计算 月利息 ，每个月可获取利息
			$borrowsList[yuehlx]  = number_format($borrowsList['yuelx'] * $borrowsList['LoanCycleMonth'],2);

		}elseif(!empty($borrowsList['LoanCycleDay']) || intval($borrowsList['LoanCycleDay']) != 0){
			//计算 月利息 天利息 ，每天可获取利息
			$borrowsList['tianlx'] = number_format($borrowsList['yuelx'] / 30,4);
			$borrowsList['tianhlx'] = number_format($borrowsList['tianlx'] * $borrowsList['LoanCycleDay'],2);
		}
		$start_date = date('Y-m-d',time());
		$borrowsList['surplus_date'] = getBetweenTwoDate($start_date,$borrowsList['ExpiredAt']);
		if($borrowsList['surplus_date'] <0 ){
			$borrowsList['surplus_date'] = "<font color='red'>结束竞标，在还款中...</font> ";
		}
		$this->assign('borrowsList',$borrowsList);

		//投资记录

		$Db_investment = D('Investment');
		$conditions_inves['did'] =  $borrowsList['bid'];
		$investmentList = $Db_investment->where($conditions_inves)->select();
		$this->assign('investmentList',$investmentList);

		//获取用户的基本信息
		$user_condition['uid']= $borrowsList['uid'];
		$userinfo = D('User')->field(true)->where($user_condition)->find();
		$userinfo['birthday'] = get_age($userinfo['birthday']);
		$userinfo['idcard'] = D('Id_card')->where($user_condition)->getField('status');;
		//身份证验证
		$this->assign('userinfo',$userinfo);

		//授信信息
		$pledge_condition['uid'] = $borrowsList['uid'];
		$pledgeList = $Db_pledge->where($pledge_condition)->find();
		$this->assign('pledgeList',$pledgeList);


		//授信域名列表
		$Db_pledge_domain = D('Pledge_domain');
		$pledge_domain_condition['pid']  = array('in', $borrowsList['pids']);
		$pledgeDomainList = $Db_pledge_domain->where($pledge_domain_condition)->select();
		$this->assign('pledgeDomainList',$pledgeDomainList);

		$Db_payment_history = D('Payment_history');
		$payment_history_con['bid'] = $borrowsList['bid'];
		$payment_history  = $Db_payment_history->where($payment_history_con)->select();
		$this->assign('payment_history',$payment_history);
		$this->display();
	}

	//立即投资
	public function investing(){
		$dkid = intval($_GET['dkid']) ? intval($_GET['dkid']) : 0;
		if($dkid <= 0){
			$this->error('进入方式不对！',U('Financing/index'));
		}
		$Db_borrows       = D('Borrows');
		//$borrows_condition['uid'] = $this->user_session['uid'];
		$borrows_condition['bid'] = $dkid;
		$borrowsInfo = $Db_borrows->where($borrows_condition)->find();
		//年利率转换为小数
		$borrowsInfo['RateFloat'] = number_format($borrowsInfo['Rate'] / 100,4);
		//还款周期，如果是月的全部转换为 天
		if($borrowsInfo['LoanCycleDay'] != 0 || !empty($borrowsInfo['LoanCycleDay'])){
			$borrowsInfo['LoanCycle'] = $borrowsInfo['LoanCycleDay'];
		}else{
			//每个月按照30天来计算
			$borrowsInfo['LoanCycle'] = $borrowsInfo['LoanCycleMonth'] * 30;
		}

		$this->assign('borrowsInfo',$borrowsInfo);
		//授信信息
		$Db_pledge = D('pledges');
		$pledge_condition['uid'] = $this->user_session['uid'];
		$pledgeList = $Db_pledge->where($pledge_condition)->find();
		$this->assign('pledgeList',$pledgeList);



		$this->display();
	}

	public function investing_now(){
		if(IS_POST){

			$Db_loan_trade_pass = D('Loan_trade_pass');
			$trade_password =trim($_POST['trade_password']);
			$trade_pass['trade_password'] = md5($trade_password);
			$trade_pass['uid']            = $this->user_session['uid'];
			$is_set_pass = $Db_loan_trade_pass->where($trade_pass)->find();
			if(empty($is_set_pass)){
				$return = array('error'=>-1,'title'=>'错误','msg'=>'交易密码错误');
				$this->ajaxReturn($return);
			}
			//查看该投资发布人是否是本人
			$borrows_condition['bid'] = intval($_POST['bid']);
			$borrows_condition['uid'] = $this->user_session['uid'];
			$can_investing =  D('Borrows')->where($borrows_condition)->find();
			if($can_investing){
				$return = array('error'=>-1,'title'=>'错误','msg'=>'不可以自己投资自己的贷款!,请选择其他用户进行贷款，现在正在为您跳转...','reloadurl'=>U('Investment/lend'));
				$this->ajaxReturn($return);
			}

			$Db_borrows = D('Borrows');
			$borrows =  $Db_borrows->where('`bid`='.intval($_POST['bid']))->find();
			if(empty($borrows)){
				$return = array('error'=>-1,'title'=>'错误','msg'=>'没有该记录的投资信息','reloadurl'=>U('Investment/lend'));
				$this->ajaxReturn($return);
			}
			/**
			 * 1、 账户资金不充足；
			   2、 借还款列表进度未达到100%而流标。
				如果您投的借入列表未满标，可以取消当前的投标，若此标满标，则无法取消。
			 */
			$Db_user = D('User');
			$userInfo  = $Db_user->field(true)->where('`uid`='.$this->user_session['uid'])->find();
			if($userInfo['now_money'] < $_POST['Amount'] ){
				$return = array('error'=>-1,'title'=>'账号余额不足','msg'=>'您的账号余额不足！,正在为您跳转...','reloadurl'=>U('Financing/index'));
				$this->ajaxReturn($return);
			}
			if($borrows['status'] == 8){
				$return = array('error'=>-1,'title'=>'投标失败','msg'=>'该借款列表进度未达到100%而流标,正在为您跳转...','reloadurl'=>U('Investment/lend'));
				$this->ajaxReturn($return);
			}
			if($borrows['needAmount'] <= 0){
				$return = array('error'=>-1,'title'=>'投标失败','msg'=>'该借款列表进度已经满，请投标其他借款,正在为您跳转...','reloadurl'=>U('Investment/lend'));
				$this->ajaxReturn($return);
			}
			//入 投资人
			$Db_investment = D('Investment');
			$investmentdata['uid']      = $this->user_session['uid'];
			$investmentdata['iname']    = $this->user_session['nickname'];
			$investmentdata['did']      = $borrows['bid'];
			$investmentdata['Amount']   = $_POST['Amount'];
			$investmentdata['itime']    = time();
			$investmentdata['status']   = 1;
			$investmentdata['Rate']     = $_POST['Rate'];
			$investmentdata['nsy']      = $_POST['nsy'];
			$investmentdata['LoanCycle']= $_POST['LoanCycle'];
			$investmentdata['Amountdx'] = $_POST['Amountdx'];
			$investmentdata['status']   = 1;

			if(intval($investmentdata['Amount']) <= 0 || empty($investmentdata['Rate']) ){
				$return = array('error'=>-1,'title'=>'错误','msg'=>'提交信息有空值。',);
				$this->ajaxReturn($return);
			}
			if($Db_investment->data($investmentdata)->add()){
				//减去用户金额，减去还需要投资金额
				$Db_user->where('`uid`='.$this->user_session['uid'])->setDec('now_money',$_POST['Amount']);
				//增加个人借出总额,先判断是否添加过
				$Db_pledges = D('Pledges');
				$pledgesresult =  $Db_pledges->where('`uid`='.$this->user_session['uid'])->find();
				if(!empty($pledgesresult)){
					$Db_pledges->where('`uid`='.$this->user_session['uid'])->setInc('lend_total',$_POST['Amount']);
				}else{
					$pledges_add['uid'] = $this->user_session['uid'];
					$pledges_add['lend_total'] = $_POST['Amount'];
					$Db_pledges->add($pledges_add);
				}

				$borrows_save_data['needAmount'] = $borrows['needAmount'] - $_POST['Amount'];//先减去还需要投资金额
				/**
				 * 说明已经达标 100% 设置【下一次（第一次）还款日期等同满标日期】 ,合同到期 = 满标当天 + 借款周期
				 */
				if($borrows_save_data['needAmount'] == 0){

					$borrows_save_data['status'] = 2; //投资已经完成 100%的进度,投资人等待还款阶段,发布人开始计算 待还总额
					$borrows_save_data['FullScaleTime'] = date('Y-m-d',time()); //投资已经完成 100%的进度,借款利息是从借款列表满标的第当天开始计算
					$borrows_save_data['NextRepayDate'] = date('Y-m-d',time()); //设置【下一次（第一次）还款日期等同满标日期】
					$FullScaleTime = date('Y-m-d',time());
					//第一次应还款时间： 满标时间 + 借款周期周期
					if($borrows['LoanCycleDay'] > 0){ //天
						$days = $borrows['LoanCycleDay'];
					}else if($borrows['LoanCycleMonth'] > 0){ //月
						//每个月按 30 天来计算
						$days = $borrows['LoanCycleMonth'] * 30;
					}
					$borrows_save_data['repayDate'] = date('Y-m-d',strtotime("$FullScaleTime  + $days day"));//第一次应还款时间
					$borrows_save_data['contractExpire'] = date('Y-m-d',strtotime("$FullScaleTime  + $days day")); // 合同到期 = 满标当天 + 借款周期

					$stay_total = $borrows['Amount'] + $borrows['zlx'] + $borrows['zglf']; //待还总额 = 本次借款总额+本次总利息 +总管理费
					$Db_pledges->where(array('uid'=>$borrows['borrowstatus']))->setInc('stay_total',$stay_total);
				}
				$borrows_save_data['investor_tatol'] = $borrows['investor_tatol'] + 1;	//总投资数
				//投资人uid以逗号(,)分隔 [一个人多次投标]
				$borrows_save_data['inves_uids'] =  $borrows['inves_uids'] ? $borrows['inves_uids'].','.$this->user_session['uid'] : $this->user_session['uid'];
				//$borrows_save_data['bid'] = $borrows['bid'];
				$borrows_save_data['invesing'] = intval((($borrows['Amount'] - $borrows_save_data['needAmount']) / $borrows['Amount']) * 100);; //投资进度
				$Db_borrows->where('`bid`='.$borrows['bid'])->data($borrows_save_data)->save();



				//冻结金额 【投标xxxx 冻结资金】
				$Db_user_money_list = M('User_money_list');
				$money_list_data['desc']       = "投标[{$borrows['did']}]冻结资金";
				$money_list_data['type']       = 4;
				$money_list_data['time']       = time();
				$money_list_data['uid']        = $this->user_session['uid'];
				$money_list_data['money']      = $_POST['Amount'];
				$money_list_data['now_money']  = $this->user_session['now_money'] -  $_POST['Amount'];
				//用户的金额减少
				$u_info = $Db_user->where(array('uid'=>$this->user_session['uid']))->setDec('now_money',$_POST['Amount']);
				//用户冻结金额增加
				$u_info = $Db_user->where(array('uid'=>$this->user_session['uid']))->setInc('freeze_money',$_POST['Amount']);
				$f_info = $Db_user_money_list->add($money_list_data);

				$return = array('error'=>0,'title'=>'投标成功','msg'=>'恭喜，您已经投标成功。','reloadurl'=>U('Investment/lend'),);
				$this->ajaxReturn($return);
			} else{
				$return = array('error'=>-1,'title'=>'错误','msg'=>'投标失败，请重试。',);
				$this->ajaxReturn($return);
			}

		}
	}
}